package ntd.util.frame.msg.service.context;

import cn.hutool.json.JSONObject;
import com.modular.system.msg.Msg;
import lombok.Data;
import ntd.util.frame.msg.bo.MsgInBO;
import ntd.util.frame.msg.bo.MsgInfo;
import ntd.util.modular.function.entity.ChannelBusiness;
import ntd.util.modular.msg.entity.SmsTemplate;

import java.util.List;

@Data
public class MsgContext {

    private MsgInBO msgInBO;
    private String action = "sendMsg";
    private ChannelBusiness channelBusiness;
    /** 渠道商下短信模板列表 */
    private List<SmsTemplate> smsTemplates;

    public static MsgContext init(MsgInBO msgInBO, ChannelBusiness channelBusiness) {
        MsgContext msgContext = init(channelBusiness);
        msgContext.setMsgInBO(msgInBO);
        return msgContext;
    }

    public static MsgContext init(Msg msg, ChannelBusiness channelBusiness) {
        MsgContext msgContext = init(channelBusiness);
        msgContext.setMsgInBO(transform(msg));
        return msgContext;
    }

    public static MsgContext init(ChannelBusiness channelBusiness) {
        MsgContext msgContext = new MsgContext();
        msgContext.setChannelBusiness(channelBusiness);
        return msgContext;
    }

    private static MsgInBO transform(Msg msg) {
        MsgInBO msgInBO = new MsgInBO();

        JSONObject jsonObject = new JSONObject(msg.getReceiverJson());
        msgInBO.setReceiverIds(jsonObject.getStr("ids"));
        msgInBO.setReceiverAlias(jsonObject.getStr("alias"));
        msgInBO.setReceiverTags(jsonObject.getStr("tags"));
        msgInBO.setReceiverPhones(jsonObject.getStr("phones"));
        msgInBO.setReceiverEmails(jsonObject.getStr("emails"));
        msgInBO.setMsgSenderUserId(msg.getSender());
        msgInBO.setDataJson(msg.getDataJson());
        msgInBO.setEnumMsgHandle(msg.getEnumMsgHandle());
        msgInBO.setChannelBusinessId(msg.getChannelBusinessId());

        MsgInfo msgInfo = new MsgInfo();
        msgInfo.setTitle(msg.getTitle());
        msgInfo.setLink(msg.getLink());
        msgInfo.setContent(msg.getContent());
        msgInBO.setMsgInfo(msgInfo);

        return msgInBO;
    }
}
